<?php

namespace app\common\behavior;

use think\Request;
use app\common\repository\user\R as UserRRepository;
use app\common\repository\article\U as ArticleURepository;
use app\common\repository\authApi\R as AuthApiRRepository;
use app\common\repository\userStatistics\U as UserStatisticsURepository;

class ActionBegin
{
    public function __construct(
        UserRRepository $userRRepository,
        ArticleURepository $articleURepository,
        AuthApiRRepository $authApiRRepository,
        UserStatisticsURepository $userStatisticsURepository
    )
    {
        $this->userRRepository = $userRRepository;
        $this->articleURepository = $articleURepository;
        $this->authApiRRepository = $authApiRRepository;
        $this->userStatisticsURepository = $userStatisticsURepository;
    }

    public function run(Request $request, $params)
    {
        $controllerName = strtolower($request->controller());
        $actionName = strtolower($request->action());
        if (!empty(request()->user)) {
            $limitApi = $this->authApiRRepository->getAuthApi(['controller' => $controllerName]);
            if (!empty($limitApi->id) && in_array($actionName, explode('|', $limitApi->actions))) {
                $userAuthApi = $this->userRRepository->getUserAuthApi(request()->user->id, $controllerName);
                if (!in_array($actionName, $userAuthApi)) {
                    header('Content-Type:application/json; charset=utf-8');
                    exit(json_encode(['data' => '未拥有权限', 'code' => config('code.user.auth.limit')]));
                }
            }
        }
        switch ($controllerName) {
            case 'page':
                if ($actionName === 'article') {
                    $articleId = $request->param('id');
                    $this->articleURepository->doArticleView($articleId);
                    $this->userStatisticsURepository->doUserViewByArticleId($articleId);
                }
                break;
            case 'user':
                if ($actionName === 'createarticlecomment') {
                    $articleId = $request->param('id');
                    $this->articleURepository->doArticleComment($articleId);
                }
                break;
            default:
                break;
        }

    }
}
